<?
header("Content-Type: text/html; charset=utf-8");

/* Database connection function */
function connectDB()
{
    mysql_connect("localhost","root","");
    mysql_selectdb("rare");    
} /* End of Database connection function */


/* getElementById Function */

/* Search function. Returns array. */
function search( $table, $cols, $query, $mode)
{
    if($mode == "FULLTEXT")
     $query = mysql_query("SELECT * FROM ".$table." WHERE MATCH  (".$cols.")  AGAINST ('".addslashes($query)."')");
    elseif($mode == "LIKE")
     $query = mysql_query("SELECT * FROM ".$table." WHERE (".$cols.") LIKE ('%".addslashes($query)."%')"); 
     
    while($result = mysql_fetch_array($query))
     $arraySearchResults[] = $result;
    return $arraySearchResults;  
} /* End of search function */



function str_separ($text, $counttext, $start = 0) {
    $sep = ' ';
     $words = explode($sep, $text);
     if ( count($words) > $counttext )
         $text = join($sep, array_slice($words, $start, $counttext));
     return $text;
 }


function showSearchResults( $query )
{
    $results = search("queries", "query, body", $query, "FULLTEXT");
    if($results)
     {
        
       
       
     foreach($results as $key=>$result)
        {
        $pos = stripos($result['body'], $query);
        if(($pos - 100) >=0 )
         $pos = $pos - 100;
        else $pos = 0;
        $prepareDesc =  substr($result['body'], $pos); 
                      
         if(strlen($prepareDesc) > 150)
          $prepareDesc = "...".str_separ($prepareDesc, 30, 1)."...";
                    
        
           $prepareDesc = str_ireplace($query, "<b>".$query."</b>", $prepareDesc);
         
         
        echo "<a href='index.php?id=".$result['id']."' class='link'>".$result['query']."</a><div class='simple'>".$prepareDesc."</div><br>";
        }
      }
}

function detect_ie()
{
    if (isset($_SERVER['HTTP_USER_AGENT']) && 
    (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))
        return true;
    else
        return false;
}

function safePost( $str )
{
    if(detect_ie() == true)
      $str =  iconv("cp1251", "utf-8", $str);
    return $str;        
}


connectDB();

if($_GET['query']) 
 
  echo  safePost(showSearchResults( safePost($_GET['query'])));

?>